                                                                                                                                                                                            <!-- src/components/Login.vue -->
<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="login-left">
        <div class="welcome-content">
          <h1>欢迎回来</h1>
          <p>请输入您的账号和密码登录系统</p>
          <div class="features">
            <div class="feature-item">
              <el-icon>
                <Check />
              </el-icon>
              <span>安全可靠的认证系统</span>
            </div>
            <div class="feature-item">
              <el-icon>
                <Check />
              </el-icon>
              <span>多因素身份验证</span>
            </div>
            <div class="feature-item">
              <el-icon>
                <Check />
              </el-icon>
              <span>实时安全监控</span>
            </div>
          </div>
        </div>
      </div>

      <div class="login-right">
        <el-card class="login-card" shadow="always">
          <div class="login-header">
            <h2>用户登录</h2>
            <p>请输入您的账户信息</p>
          </div>

          <el-form class="login-form" :model="loginForm" :rules="loginRules" ref="loginFormRef"
            @submit.prevent="handleLogin" size="large">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" placeholder="请输入用户名" :prefix-icon="User" clearable />
            </el-form-item>

            <el-form-item prop="password">
              <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" :prefix-icon="Lock"
                show-password clearable @keyup.enter="handleLogin" />
            </el-form-item>

            <div class="login-options">
              <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
              <div style="display:flex;align-items:center;gap:12px">
                <el-radio-group v-model="loginForm.role">
                  <el-radio label="user">用户</el-radio>
                  <el-radio label="admin">管理员</el-radio>
                </el-radio-group>
              </div>
              <el-link type="primary" :underline="false">忘记密码？</el-link>
            </div>

            <el-form-item>
              <el-button class="login-button" type="primary" :loading="loading" @click="handleLogin">
                {{ loading ? '登录中...' : '立即登录' }}
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 屏幕中央错误覆盖层（点击关闭或点击按钮关闭） -->
          <div v-if="errorMessage" class="center-error-overlay" @click.self="clearError">
            <div class="center-error-box">
              <div class="center-error-title">错误</div>
              <div class="center-error-message">{{ errorMessage }}</div>
              <div class="center-error-actions">
                <el-button type="primary" size="small" @click="clearError">关闭</el-button>
              </div>
            </div>
          </div>

          <div class="login-footer">
            <p class="register-tip">
              还没有账号？<el-link type="primary" :underline="false" @click.prevent="goRegister">立即注册</el-link>
            </p>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { ElForm } from 'element-plus'
import { ElMessage } from 'element-plus'
import { User, Lock, Check } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import api from '../utils/api'

// 获取路由实例以便跳转到注册页
const router = useRouter()

const goRegister = (): void => {
  router.push('/register')
}

// 定义类型
interface LoginForm {
  username: string
  password: string
  remember: boolean
  role?: 'user' | 'admin'
}

// 响应式数据
const loginFormRef = ref<InstanceType<typeof ElForm>>()
const loading = ref(false)
const errorMessage = ref('')

const clearError = (): void => {
  errorMessage.value = ''
}

const loginForm = reactive<LoginForm>({
  username: '',
  password: '',
  remember: false
  ,role: 'user'
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 12, message: '用户名长度在 3 到 12 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' }
  ]
}


const FIXED_ADMIN = { username: 'panchenyang', password: '123456' }

const handleLogin = async (): Promise<void> => {
  if (!loginFormRef.value) return

  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return

    loading.value = true

    // 模拟登录请求
    // await new Promise(resolve => setTimeout(resolve, 1500))

    // ElMessage.success('登录成功！')
    // console.log('登录信息:', { ...loginForm })
    // router.push('/frontpage')
    // axios.get('/api/search')
    //   .then(response => {
    //     console.log('Axios works! Response status:', response.status);
    //   })
    //   .catch(error => {
    //     console.error('Error:', error.message);
    //   });
    // 使用封装的 api 调用后端登录接口（Vite proxy 会把 /api 转发到后端）
    try {
      // 先检查是否是本地固定管理员凭据
      if (loginForm.username === FIXED_ADMIN.username && loginForm.password === FIXED_ADMIN.password) {
        // 强制为 admin 角色并直接通过登录
        console.log('local fixed admin login')
        errorMessage.value = ''
        try { localStorage.setItem('username', loginForm.username) } catch(e) {}
        try { localStorage.setItem('role', 'admin') } catch(e) {}
        await router.replace('/admin/users')
        loading.value = false
        return
      }

      const resp: any = await api.post('/login', {
        userName: loginForm.username,
        password: loginForm.password,
        role: loginForm.role
      })

      console.log('login response:', resp)
      // 后端可能以多种形式返回 operationResult，这里做更宽松的判断
      const op = resp?.operationResult
      const ec = resp?.errorCode
      // widen success detection to cover several backend enum/number/string serializations
      const isSucc =
        op === 'SUCC' ||
        (typeof op === 'string' && op.toUpperCase().includes('SUCC')) ||
        (op && op.name && String(op.name).toUpperCase().includes('SUCC')) ||
        ec === 0 || ec === 'OK' || String(ec).toUpperCase().includes('OK')
      if (isSucc) {
        console.log('登录成功')
        errorMessage.value = ''
        // 判断是否为固定管理员登录（固定管理员不需要后端注册校验）
        const isFixedAdminLogin = (loginForm.username === FIXED_ADMIN.username && loginForm.password === FIXED_ADMIN.password)

        // 非固定管理员登录时，额外检查该用户名是否已在系统中注册；未注册则拒绝进入日程管理
        if (!isFixedAdminLogin) {
          let registered = false
          try {
            const checkResp: any = await api.get('/user/search', { params: { username: loginForm.username } })
            if (checkResp && checkResp.operationResult === 'SUCC') registered = true
          } catch (checkErr) {
            console.warn('user/search 检查失败，尝试 /users 列表查找', checkErr)
            try {
              const usersResp: any = await api.get('/users')
              const list = Array.isArray(usersResp?.data) ? usersResp.data : (Array.isArray(usersResp) ? usersResp : [])
              if (list && list.length) {
                const found = list.find((u: any) => u.username === loginForm.username || u.userName === loginForm.username)
                if (found) registered = true
              }
            } catch (listErr) {
              console.warn('users 列表检查也失败，无法确认注册状态', listErr)
            }
          }
          if (!registered) {
            const msg = '该账号未注册，无法登录日程管理，请先注册或联系管理员'
            errorMessage.value = msg
            try { ElMessage.error(msg) } catch (e) {}
            loading.value = false
            return
          }
        }

        try { localStorage.setItem('username', loginForm.username) } catch(e) {}
        // 如果用户选择了管理员但并非固定管理员凭证，则强制作为普通用户处理，避免注册用户通过选择 admin 进入管理界面
        let effectiveRole = String(loginForm.role || 'user')
        if (loginForm.role === 'admin' && !isFixedAdminLogin) {
          // 不是固定管理员，但尝试以管理员身份登录 -> 强制降级为用户
          effectiveRole = 'user'
          try { ElMessage.info('该账户无管理员权限，已作为普通用户登录') } catch (e) {}
        }
        try { localStorage.setItem('role', effectiveRole) } catch(e) {}
        // 使用 replace 避免回退回登录页，并捕获导航错误
        try {
          // 根据角色跳转
          if (effectiveRole === 'admin') {
            await router.replace('/admin/users')
          } else {
            await router.replace('/dashboard')
          }
          console.log('navigation succeeded')
        } catch (navErr) {
          console.error('navigation failed with replace:', navErr)
          try {
            console.log('trying push as fallback')
            await router.push('/dashboard')
            console.log('push fallback succeeded')
          } catch (pushErr) {
            console.error('push fallback also failed:', pushErr)
          }
        }
      } else {
        errorMessage.value = resp?.errorMsg || '登录失败，请检查用户名或密码'
      }
    } catch (err: any) {
      console.error('登录异常', err)
      let serverMsg: any = err?.response?.data?.errorMsg ?? err?.response?.data ?? err?.message ?? ''
      if (typeof serverMsg === 'object') serverMsg = JSON.stringify(serverMsg)
      errorMessage.value = String(serverMsg) || '登录异常，请稍后重试'
    }


  } catch (error) {
    ElMessage.error('登录失败，请检查输入信息')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
}

.login-wrapper {
  display: flex;
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  min-height: 600px;
}

.login-left {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60px 40px;
  display: flex;
  align-items: center;
}

.welcome-content h1 {
  font-size: 2.5rem;
  margin-bottom: 16px;
  font-weight: 600;
}

.welcome-content p {
  font-size: 1.1rem;
  margin-bottom: 40px;
  opacity: 0.9;
}

.features {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 1rem;
}

.feature-item .el-icon {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  padding: 4px;
}

.login-right {
  flex: 1;
  padding: 40px;
  display: flex;
  align-items: center;
}

.login-card {
  border: none;
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  color: #303133;
  font-size: 1.8rem;
  margin-bottom: 8px;
  font-weight: 600;
}

.login-header p {
  color: #909399;
  font-size: 0.9rem;
}

.login-form {
  margin-bottom: 20px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 1.1rem;
  border-radius: 8px;
}

.login-footer {
  text-align: center;
}

.form-error {
  display: flex;
  justify-content: center;
  max-width: 360px;
  margin: 0 auto 16px auto;
  padding: 4px 8px;
}

/* 居中错误覆盖层 */
.center-error-overlay {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.35);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}
.center-error-box {
  background: #fff;
  padding: 20px 24px;
  border-radius: 8px;
  width: 360px;
  box-shadow: 0 8px 24px rgba(0,0,0,0.2);
  text-align: center;
}
.center-error-title {
  font-weight: 600;
  margin-bottom: 8px;
}
.center-error-message {
  color: #f56c6c;
  margin-bottom: 12px;
}
.center-error-actions {
  display: flex;
  justify-content: center;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin: 20px 0;
}

.social-btn {
  width: 44px;
  height: 44px;
  border: 1px solid #dcdfe6;
  background: white;
}

.social-btn.wechat:hover {
  border-color: #07c160;
  color: #07c160;
}

.social-btn.qq:hover {
  border-color: #12b7f5;
  color: #12b7f5;
}

.social-btn.weibo:hover {
  border-color: #e6162d;
  color: #e6162d;
}

.register-tip {
  color: #909399;
  font-size: 0.9rem;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-wrapper {
    flex-direction: column;
    margin: 20px;
  }

  .login-left {
    padding: 40px 20px;
  }

  .login-right {
    padding: 30px 20px;
  }

  .welcome-content h1 {
    font-size: 2rem;
  }
}
</style>